package second.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: heweiwei
 * @Date: 2/8/25 PM3:19
 * @Description:
 */
public class ThreadPoolCompletionCheck {
    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 提交任务
        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            executor.submit(() -> {
                try {
                    // 模拟任务执行
                    Thread.sleep(1000);
                    System.out.println("Task " + taskId + " completed");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        // 启动关闭序列
        executor.shutdown();

        try {
            // 等待所有任务执行完毕，最多等待 5 秒
            if (executor.awaitTermination(5, TimeUnit.SECONDS)) {
                System.out.println("All tasks completed.");
            } else {
                System.out.println("Not all tasks completed within the timeout.");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
